package com.young.core.manager.impl;

import com.google.gson.GsonBuilder;
import com.young.common.query.Pagination;
import com.young.common.query.Query;
import com.young.core.dao.TraceDao;
import com.young.core.domain.TraceDO;
import com.young.core.enums.HttpStatusEnum;
import com.young.core.manager.TraceManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Date;


@Component
public class TraceManagerImpl implements TraceManager {

    public static final GsonBuilder G_BUILDER = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

    @Autowired
    private TraceDao traceDao;

    @Override
    public Pagination<TraceDO> query(Query query) {
        return traceDao.query(query);
    }

    @Override
    public void insert(TraceDO trace) {
        trace.setContent("");
        traceDao.insert(trace);
    }

    @Override
    public TraceDO get(String traceId) {
        return traceDao.get(traceId);
    }

    @Override
    public void append(String traceId, TraceDO.NodeTrace nodeTrace) {
        TraceDO trace = new TraceDO();
        trace.setTraceId(traceId);
        trace.setContent(G_BUILDER.create().toJson(nodeTrace));
        int status = nodeTrace.getStatus();
        if (HttpStatusEnum.isSSuccess(status)) {
            trace.setSuccess(true);
        }
        this.traceDao.update(trace);
    }

    @Override
    public int deleteExpired(Date time,Collection<String> excludes) {
        return this.traceDao.deleteExpired(time,excludes);
    }

}
